# coding:utf-8
from contextlib import nullcontext
import re
import json
import tushare as ts
import pandas as pd
from PyQt6.QtCore import Qt, QEasingCurve, QUrl
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QWidget, QVBoxLayout
from qfluentwidgets import (SingleDirectionScrollArea, SmoothScrollArea, ToolTipFilter, PixmapLabel,
                            ScrollArea, ImageLabel, HorizontalPipsPager, PipsScrollButtonDisplayMode, VerticalPipsPager)
from qframelesswindow.webengine import FramelessWebEngineView

from .template_info_view import BaseInfoTemplateView
from .base_gallery_view import GalleryInterface
from .common.translator import Translator
from service.stock_service import getRealTimeStock
from common.utils.JsonReplace import JsonPlaceholderReplacer


class StockDayView(BaseInfoTemplateView):
    """ Scroll interface """

    def __init__(self,   parent=None):
        t = Translator()
        super().__init__(
            "StockDayView",
            parent=parent
        )

        # 添加一个报表
        self.addEcahtMainView("stock_day")

    def doSearch(self):
        print(f"查询股票{self.searchKey}")
        self.updateEchatData()

    def getEchatData(self, jsonData: dict):
        if self.searchKey is not None and self.searchKey != "":
            print(f"校验通过{self.searchKey}")

            stock_data = self.get_stock_data()
            dates_data = self.get_datas(stock_data)
            kline_data = self.get_kline_data(stock_data)
            point_data = self.get_point_data(stock_data)
            mark_data = self.get_markline_data(stock_data)

            replacer = JsonPlaceholderReplacer(jsonData)
            # 时间轴
            replacer.replace_placeholder("__DATAS__", dates_data)
            # 主线数据
            replacer.replace_placeholder("__STOCK_DATA__", kline_data)
            # 标记点数据
            replacer.replace_placeholder("__POINT_DATA__", point_data)
            # 辅助线数据
            replacer.replace_placeholder("__MARK_DATA__", mark_data)

            print(f"最终解析对象{replacer.get_modified_json()}")
            return replacer.get_modified_json()
        else:
            return jsonData

    def get_stock_data(self):
        # # 设置你的 Token （这里方便以后的Demo放在了TXT文件中）
        with open('D:\\code\\python\\tushareToken.txt', 'r', encoding='utf-8') as file:
            token = file.read().strip()
            ts.set_token(token)
        pro = ts.pro_api()

        # 获取某支股票的每日行情，示例为 '600519.SH'
        df = pro.daily(ts_code='600519.SH',
                       start_date='20240101', end_date='20240313')

        # 将日期设置为索引并按时间排序
        df.index = pd.to_datetime(df['trade_date'])
        df = df.sort_index()

        # 提取需要的列（日期、开盘、收盘、最高、最低）
        return df[['open', 'close', 'high', 'low']]

    def get_kline_data(self, stock_data):
        # 生成 K 线图所需的数组
        kline_data = []
        for row in stock_data.itertuples():
            kline_data.append([row.open, row.close, row.low, row.high])

        return kline_data

    def get_datas(self, stock_data):
        # 日期
        return stock_data.index.strftime('%Y-%m-%d').tolist()

    def get_point_data(self, stock_data):
        return [{
            "name": 'highest value',
            "type": 'max',
            "valueDim": 'highest'
        },
            {
            "name": 'lowest value',
            "type": 'min',
            "valueDim": 'lowest'
        }]

    def get_markline_data(self, stock_data):
        # 计算收盘价的平均值
        average_price = stock_data['close'].mean()

        # 生成 markLine 数据
        markline_data = {
            'data': [
                {
                    'yAxis': average_price,  # 将 y 轴的值设置为均值
                    'name': '平均值',
                    'lineStyle': {
                        'color': '#FF0000',  # 线条颜色
                        'type': 'dashed',    # 线条类型（虚线）
                        'width': 2           # 线条宽度
                    },
                    'label': {
                        'formatter': f'平均值: {average_price:.2f}',  # 显示的文本
                        'position': 'end',    # 文本位置
                        'color': '#FF0000'    # 文本颜色
                    }
                }
            ]
        }
        return markline_data
